<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="query.username" clearable placeholder="请输入账号" @keyup.enter.native="search" />
      <el-input v-model.trim="query.realName" placeholder="请输入用户名" clearable @keyup.enter.native="search" />
      <el-input v-model.trim="query.roleName" placeholder="请输入角色名称" clearable @keyup.enter.native="search" />
      <el-select v-model="query.status" placeholder="请选择状态" clearable>
        <el-option v-for="item in status" :key="item.key" :label="item.displayName" :value="item.key" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t('table.search') }}
      </el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
        新增
      </el-button>
      <el-table :data="userList" highlight-current-row border :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="username" label="账号"/>
        <el-table-column prop="realname" label="真实姓名" />
        <el-table-column prop="roleName" label="角色名称">
          <template slot-scope="{row:{role}}">
            {{ role && role.roleName }}
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="联系方式"/>
        <el-table-column prop="email" label="邮箱"/>
        <!-- <el-table-column prop="groupId" label="部门" sortable>
          <template slot-scope="{row}">
            <span> {{ formatMaterial(row.groupId) }} </span>
          </template>
        </el-table-column> -->
        <el-table-column prop="status" label="状态">
          <template slot-scope="{row:{status}}">
            <el-tag :type="status == 0 ? 'success' : 'danger'" size="small">{{ status == 0 ? '已启用' : '未启用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="{row}">
            <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="300px">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleEdit(row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button type="primary" size="mini" @click="reset(row)">
              重置密码
            </el-button>
            <el-button :type="row.status == 0 ? 'danger' : 'success'" size="mini" @click="handleDelete(row)">
              {{ row.status == 0 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
        @pagination="getUserPage" />
      <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="user.id ? '编辑用户' : '新建用户'"
        @closed="dialogClose">
        <el-form :model="user" :rules="rules" ref="ruleForm" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model.trim="user.username" :disabled="!!user.id" maxlength="20" placeholder="请输入用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realname">
                <el-input v-model.trim="user.realname" maxlength="20" placeholder="真实姓名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="mobile">
                <el-input v-model.trim="user.mobile" maxlength="20" placeholder="联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model.trim="user.email" maxlength="50" placeholder="邮箱" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="部门" prop="groupId">
                <el-select style="width: 100%;" v-model="user.groupId" placeholder="部门" clearable filterable>
                  <el-option v-for="item in groups" :key="item.id" :label="`${item.groupName} (${item.groupNo})`"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="角色" prop="roleId">
                <el-select style="width: 100%;" v-model="user.roleId" placeholder="角色" class="filter-item" clearable
                  filterable>
                  <el-option v-for="item in roles" :key="item.id"
                    :label="`${item.roleName} (${roleTypes[item.roleType].displayName})`" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="user.status" size="small">
                  <el-radio-button v-for="state in status" :key="state.key" :label="state.key">
                    {{ state.displayName }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible = false">
            {{ $t('permission.cancel') }}
          </el-button>
          <el-button type="primary" @click="submit">
            {{ $t('permission.confirm') }}
          </el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getUserPage, addUser, updateUser, deleteUser, resetPwd } from '@/api/user'
import { getInfoAll as getGroups } from '@/api/groupinfo'
import { getRoleList } from '@/api/role'
import { deepClone, refreshArr, arraryRemove } from '../../../utils'
import { validList } from '@/api/supplier'
const defaultUser = {
  email: '',
  id: '',
  username: '',
  realName: '',
  groupId: '',
  roleId: '',
  tel: '',
  status: 0,
  createTime: '',
  mobile: ''

}

const status = [
  { key: 0, displayName: '启用' },
  { key: 1, displayName: '禁用' }
]

const roleTypes = [
  { key: 0, displayName: '管理员' },
  { key: 1, displayName: '厂商' },
  { key: 2, displayName: '供应商' }
]
const validatephone = (rule, value, callback) => {
  if (value == '') {
    callback(new Error('请输入手机号'))
  } else if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) {
    callback(new Error('手机号格式不正确'))
  } else {
    callback()
  }
}
const validateEmail = (rule, value, callback) => {
  if (value == '') {
    callback(new Error('请输入邮箱'))
  } else if (!/([\w\-]+\@[\w\-]+\.[\w\-]+)/.test(value)) {
    callback(new Error('邮箱式不正确'))
  } else {
    callback()
  }
}
export default {
  name: 'Users',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        realname: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
        ],
        mobile: [
          { required: true, validator: validatephone, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        roleId:[
        { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      checkStrictly: false,
      loading: [],
      user: Object.assign({}, defaultUser),
      total: 0,
      status: Object.freeze(status),
      roleTypes: Object.freeze(roleTypes),
      query: {
        pageIndex: 1,
        pageSize: 10,
        username: '',
        realName: '',
        status: ''
      },
      currentPage: 1,
      pagesize: 10,
      userList: [],
      groups: [],
      roles: []
    }
  },
  computed: {
    userDetial() {
      return this.user
    }
  },
  mounted() {
    this.getUserPage()
    this.getGroupList()
  },
  methods: {
    dialogClose() {
      this.$refs['ruleForm'].resetFields()
    },
    getGroupList() {
      getGroups()
        .then(res => {
          this.groups = res
        })
    },
    formatMaterial(groupId) {
      const data = this.groups.find((m) => m.id === groupId)
      return data ? data.groupName : ''
    },
    reset(row) {
      this.$confirm('重置后密码是Aa123456,确认重置密码么？', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await resetPwd(row.id)
        this.$message.success('重置成功')
      }).catch(err => console.error(err))
    },
    async getUserPage() {
      const { list, total } = await getUserPage(this.query)
      this.userList = list
      this.total = total
    },
    async getRoleList() {
      this.roles = await getRoleList()
    },
    search() {
      this.currentPage = 1
      this.getUserPage()
    },
    handleAdd() {
      this.user = Object.assign({}, defaultUser)
      this.dialogVisible = true
      this.getRoleList()
    },
    handleEdit(row) {
      this.user = deepClone(row)
      this.getRoleList()
      this.dialogVisible = true
    },
    handelDel(row){

    },
    handleSizeChange(size) {
      this.query.pageSize = size
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage
    },
    handleDelete(row) {
      const s = row.status == 1 ? '启用' : '禁用'
      this.$confirm(`确认${s}用户?`, '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteUser(row.id)
        this.$message({
          type: 'success',
          message: `${s}成功！`
        })
        this.getUserPage()
        // refreshArr(this.userList, user => user.iID === this.user.iID, this.user)
      }).catch(err => console.error(err))
    },
    submit() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          const isEdit = !!this.user.id
          if (isEdit) {
            await updateUser(this.user.id, this.user)
            this.$message.success('编辑成功')
            this.getUserPage()
          } else {
            const {id,createTime} = await addUser(this.user)
            this.$message.success('新增成功')
            this.getUserPage()
            this.user.id = id
            this.user.createTime = createTime
          }
          this.dialogVisible = false
        }
      })
    }
  }
}
</script>
